<?php
namespace App\HttpController\Pudu;

use App\Common\Controller\Rest;

class WashRecords extends Rest
{
    public $modelName = 'WashRecord'; // model 类名称

    /**
     * 用户查看自身洗肠记录
     *
     * @return void
     */
    public function GETIndex()
    {
        if ($this->role != 0) {

            $userInfo = $this->model('Member')->where(['id' => $this->param['userId']])->find();
            switch ($userInfo['roleId']) {
                case 1:
                    $this->param['id'] = $this->param['userId']; // 查看自己的洗肠记录
                    break;
                case 2:
                    // TODO 市代理  可查看下属店铺 和  下属区县
                    $this->param['shopId'] = $this->param['userId']; // 查看自己店铺的洗肠记录
                    unset($this->param['userId']);
                    break;
                default:
                    $this->error(['msg' => '权限错误!']);
                    break;
            }
        }

        if (isset($this->param['Id'])) {
            $res = $this->model()->getDataById($this->param['Id']);
        } else {
            $res = $this->model()->getDataList($this->param);
        }
        $this->result($res, ['msg' => self::$model->getError(), 'data' => $res]);
    }

    /**
     * 新增洗肠记录
     *
     * @return void
     */
    public function POSTIndex()
    {
        // TODO 只有店铺能够对本店铺会员新增
        $this->abort(isset($this->param['shopUserId']), ['msg' => '请选择进行肠疗的用户!']);
        $Member = $this->model('Member');
        $memberInfo = $Member->where(['shopId' => $this->param['userId']])->where(['id' => $this->param['shopUserId']])->find();

        // TODO 确保该用户还有洗肠次数
        $this->abort($memberInfo, ['msg' => '用户不属于该店铺!']);
        $this->abort($memberInfo['washTimes'], ['msg' => '洗肠次数已用完!']);

        // TODO 整理数据
        $artificer = isset($this->param['artificer']) ? $this->param['artificer'] : null;

        $shopUsername = $Member->where(['id' => $this->param['userId']])->value('username');

        $insertData = [
            'userId' => $this->param['shopUserId'], // 洗肠用户id shopUserId
            'shopId' => $this->param['userId'],
            'shopUsername' => $shopUsername,
            'washUsername' => $memberInfo['username'],
            'artificer' => $artificer,
        ];
        // TODO 扣除用户账户洗肠次数一次

        $Member->startTrans();
        try {
            $res = $this->model()->createData($insertData);
            $res2 = $Member->where(['id' => $this->param['shopUserId']])->setDec('washTimes', 1);
            $Member->commit();
        } catch (\Exception $e) {
            $Member->rollback();
            $this->error(['msg' => $e->getMessage()]);
        }

        $this->result();
    }
}
